<template>
  <div>
    <VuiSplitpanes class="default-theme" :style="{ height: height + 'px' }">
      <VuiPane min-size="10" size="20">
        <div class="h-full p-1">
          <!-- 查询表单 -->
          <el-form ref="SelectFef" label-position="top" label-width="120px" :model="queryForm" size="small">
            <el-form-item v-for="item in queryFormList" :key="item.QUERY_COLUMN" :label="item.COLUMN_DESC">
              <el-input v-if="item.CONTROL_TYPE === 'text'" v-model="queryForm[item.QUERY_COLUMN]" class="itemForm" />
              <el-date-picker
                v-else-if="item.CONTROL_TYPE === 'date'"
                v-model="queryForm[item.QUERY_COLUMN]"
                :end-placeholder="translateTitle('Dams.CustomReport.结束时间')"
                :range-separator="translateTitle('Dams.CustomReport.至')"
                :start-placeholder="translateTitle('Dams.CustomReport.开始时间')"
                style="width: 100%"
                type="daterange"
                value-format="YYYY-MM-DD"
              />
              <el-select
                v-else-if="item.CONTROL_TYPE === 'select'"
                v-model="queryForm[item.QUERY_COLUMN]"
                clearable
                :multiple="item.CHECKBOX_FLAG === 'Y' ? true : false"
                style="width: 100%"
                @focus="getSelectData(item)"
              >
                <el-option v-for="i in selectData" :key="i.CODE_ID" :label="i.PUTAWAY_NODE_DESCRC" :value="i.CODE_ID" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="queryClick">{{ translateTitle('Dams.CustomReport.查询') }}</el-button>
              <el-button @click="resetClick">{{ translateTitle('Dams.CustomReport.重置') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </VuiPane>
      <VuiPane min-size="10" size="80">
        <div class="h-full p-1">
          <div class="buttonGroup">
            <div>
              <el-button v-if="isExport" round type="primary" @click="exportFunc">
                <vui-icon icon="arrow-down-circle-fill" />
                {{ translateTitle('Dams.CustomReport.导出') }}
              </el-button>
              <el-button v-if="isPrint" round type="primary" @click="printFunc">
                <vui-icon icon="printer-fill" />
                {{ translateTitle('Dams.CustomReport.打印') }}
              </el-button>
            </div>
            <div>
              <vxe-button class="refresh-btn" size="mini" @click="onRefresh">
                <vui-icon :class="{ roll: hasClickRefreshLoading }" icon="refresh-line" />
              </vxe-button>
              <vxe-button class="refresh-btn" size="mini" @click="showCustomOption = !showCustomOption">
                <vui-icon icon="list-settings-line" />
              </vxe-button>
            </div>

            <CustomOption
              :active="showCustomOption"
              :btn-name="translateTitle('Ve.elements.确定')"
              :columns="tablesColumn"
              :is-save="false"
              @saveToTable="saveToTable"
            />
          </div>
          <div class="tableContent">
            <vxe-table
              ref="reportTable"
              border
              :column-config="{ resizable: true }"
              :data="tableList"
              height="auto"
              :loading="hasClickRefreshLoading"
              :row-config="{ isHover: true, isCurrent: true }"
              show-header-overflow
              show-overflow
              :sortable="true"
              stripe
            >
              <vxe-column type="checkbox" width="60" />
              <vxe-column
                v-for="(item, index) in reportTableList"
                :key="index"
                :field="item.COLUMNNAME"
                min-width="80"
                sortable
                :title="item.COLUMN_DESC"
              />
            </vxe-table>
          </div>
          <vxe-pager
            v-model:current-page="currentPage"
            v-model:page-size="pagesize"
            align="right"
            :page-sizes="[50, 100, 150, 200]"
            :total="total"
            @page-change="currentChange"
          />
        </div>
      </VuiPane>
    </VuiSplitpanes>
    <VuiModal v-if="showModal" v-model="showModal">
      <template #title>{{ translateTitle('Ve.elements.提示') }}</template>
      <div class="special-situation-detail-content"></div>
    </VuiModal>
    <Download
      v-if="downloadModal"
      :checkboxlist="$refs.reportTable.getCheckboxRecords()"
      download-methods="wms.common.report.export"
      :is-modal="downloadModal"
      :search-form="downloadParams"
      search-table-methods="*.configRecord.query"
      sub-system="wms"
      :table-column="tablesColumn"
      :tablelist="tableList"
      @close="downloadClose"
    />
  </div>
</template>

<script>
  import { translateTitle } from '@/utils/i18n'
  import { processingConstant } from '@ve/utils/utils'
  import request from '@/utils/request'
  import { getList } from '@/project/dams/api/home'
  import { GFCD } from '@/utils/utils'
  import { print } from '@ve/utils/print'
  import { webapp_ws_create } from '@ve/utils/print/grwebapp'
  import Download from '../../components/download.vue'
  import CustomOption from '@/ve/elements/basic/uiTable/customOption.vue'
  import cloneDeep from 'lodash/cloneDeep'
  export default {
    name: 'CustomReportPage',
    components: { Download, CustomOption },
    data() {
      return {
        height: 400,
        id: '',
        showCustomOption: false,
        queryFormList: [], //查询表单头部数据源
        queryForm: {}, //查询表单
        reportTableList: [], //表格头部数据
        tablesColumn: [],
        tableList: [], //表格表体数据
        hasClickRefreshLoading: false,
        isExport: false,
        isPrint: false,
        downloadModal: false,
        printNumber: '', //打印模板号
        ORG_ID: '',
        selectData: [], //下拉框数据
        pagesize: 50,
        total: 0,
        currentPage: 1,
        showModal: false,
        downloadParams: {},
        catchReportTableList: [],
      }
    },
    computed: {},
    created() {
      this.id = this.$route.name
      this.ORG_ID = processingConstant(this, '#ORG_ID#')
      this.getQueryForm()
      this.getReportTable()
      this.getFuncButton()
      this.getTableData(this.currentPage, this.pagesize)
    },
    mounted() {
      this.getHeight()
    },
    methods: {
      translateTitle,
      getHeight() {
        this.height = document.documentElement.clientHeight - 40 - 20
      },
      saveToTable({ data, showCustomOption }) {
        let selectColms = data.filter((x) => x.visible === true)
        this.showCustomOption = showCustomOption
        if (!showCustomOption && data.length > 0) {
          let list = []
          selectColms.forEach((item, index) => {
            this.catchReportTableList.forEach((x) => {
              if (item.porp === x.COLUMNNAME) {
                list[index] = x
              }
            })
          })
          this.reportTableList = list
        }
      },
      onRefresh() {
        this.hasClickRefreshLoading = true
        this.getTableData(this.currentPage, this.pagesize)
      },
      //获取表格表头数据
      async getReportTable() {
        try {
          let paramsData = { '#LIMIT#': 1, '#PAGE_SIZE#': 50, ORG_ID: this.ORG_ID, REPORT_ID: this.id }
          let res = await getList(`${GFCD('dams').domain}${this.$store.getters['user/appCodeUrl']}`, {
            data: JSON.stringify(paramsData),
            method: '*.configRecordDetails.query',
          })
          this.reportTableList = res.data['*.configRecordDetails.query'].data
          this.reportTableList.forEach((x) => {
            this.tablesColumn.push({
              label: x.COLUMN_DESC,
              porp: x.COLUMNNAME,
              name: x.COLUMN_DESC,
              title: x.COLUMN_DESC,
              visible: true,
            })
          })
          this.catchReportTableList = cloneDeep(this.reportTableList)
        } catch (err) {
          console.log(err)
        }
      },
      //查询表单表头数据
      async getQueryForm() {
        try {
          //获取查询表单数据源
          let paramsData = { '#LIMIT#': 1, '#PAGE_SIZE#': 50, ORG_ID: this.ORG_ID, REPORT_ID: this.id }
          let res = await getList(`${GFCD('dams').domain}${this.$store.getters['user/appCodeUrl']}`, {
            data: JSON.stringify(paramsData),
            method: '*.configRecordWhere.query',
          })
          //筛选时间控件
          this.queryFormList = res.data['*.configRecordWhere.query'].data

          this.queryFormList.forEach((item) => {
            if (item.CONTROL_TYPE === 'date') {
              item.COLUMN_DESC = translateTitle('Dams.CustomReport.时间')
              item.QUERY_COLUMN = 'CREATION_TIME'
            }
          })
          let map = new Map()
          this.queryFormList = this.queryFormList.filter((item) => !map.has(item.QUERY_COLUMN) && map.set(item.QUERY_COLUMN))
        } catch (err) {
          console.log(err)
        }
      },
      //获取表格表体数据
      async getTableData(currentPage, pagesize) {
        try {
          let params = JSON.parse(JSON.stringify(this.queryForm))
          Object.keys(params).forEach((x) => {
            if (x !== 'CREATION_TIME' && params[x] && Array.isArray(params[x])) {
              let arrToStr = params[x].join(',')
              params[x] = arrToStr
            }
          })
          params['#LIMIT#'] = currentPage
          params['#PAGE_SIZE#'] = pagesize
          params.ORG_ID = this.ORG_ID
          params.REPORT_ID = this.id
          if (params.CREATION_TIME) {
            params['CREATION_TIME_start'] = params.CREATION_TIME[0]
            params['CREATION_TIME_end'] = params.CREATION_TIME[1]
            delete params.CREATION_TIME
          }
          this.downloadParams = params
          let res = await getList(`${GFCD('dams').domain}${this.$store.getters['user/appCodeUrl']}`, {
            data: JSON.stringify(params),
            method: '*.configRecord.query',
          })
          this.tableList = res.data.data
          this.total = res.data.count
          this.hasClickRefreshLoading = false
        } catch (err) {
          console.log(err)
        }
      },
      //获取功能组数据
      async getFuncButton() {
        try {
          let paramsData = { '#LIMIT#': 1, '#PAGE_SIZE#': 50, ORG_ID: this.ORG_ID, REPORT_ID: this.id }
          let res = await getList(`${GFCD('dams').domain}${this.$store.getters['user/appCodeUrl']}`, {
            data: JSON.stringify(paramsData),
            method: '*.record.header.query',
          })
          let item = res.data['*.record.header.query'].data[0]
          this.isExport = item.EXPORT_FLAG === 'Y' ? true : false
          this.isPrint = item.PRINT_FLAG === 'Y' ? true : false
          this.printNumber = item.PRINT_NUMBER
        } catch (e) {
          console.log(e)
        }
      },
      //获取下拉数据
      async getSelectData(val) {
        let paramsData = { '#LIMIT#': 1, '#PAGE_SIZE#': 50, ORG_ID: this.ORG_ID, CODE: val.CODE }
        try {
          let res = await getList(`${GFCD('dams').domain}${this.$store.getters['user/appCodeUrl']}`, {
            data: JSON.stringify(paramsData),
            method: '*.system.code.record.select',
          })
          this.selectData = res.data['*.system.code.record.select'].data
        } catch (err) {
          console.log(err)
        }
      },
      //查询
      queryClick() {
        this.getTableData(this.currentPage, this.pagesize)
      },
      //重置
      resetClick() {
        this.queryForm = {}
        this.getTableData(this.currentPage, this.pagesize)
      },
      //切换分页
      currentChange({ currentPage, pageSize }) {
        this.currentPage = currentPage
        this.pagesize = pageSize
        this.getTableData(this.currentPage, this.pagesize)
      },
      downloadClose() {
        this.downloadModal = false
      },
      //打印
      printFunc() {
        let create = webapp_ws_create(
          () => {},
          (value, newNode) => {
            console.log('测试打印开始')
            if (value === false) {
              this.showModal = true
              this.$nextTick(() => {
                console.log(document.querySelector('.special-situation-detail-content'))
                document.querySelector('.special-situation-detail-content')?.appendChild(newNode)
              })
            }
          }
        )
        console.log(create)
        let api = '/wms/wms-web'
        let method = 'wms.report.print'
        let selectData = this.$refs.reportTable.getCheckboxRecords()
        selectData = selectData.length > 0 ? selectData : this.tableList
        let _data = {
          REPORT_CODE: this.printNumber,
          ORG_ID: this.ORG_ID,
          WAREHOUSE_ID: this.$store.getters['user/wareHoseId'],
          selectData: selectData,
          PRINTTYPE: 'manual',
        }
        return request({
          url: GFCD('dams', 'domain') + api,
          method: 'post',
          data: {
            data: JSON.stringify(_data),
            method: method,
          },
        })
          .then((res) => {
            this.loading = false
            console.log('测试打印数据', res.data)
            //解密
            // console.log(decryptd(res))
            print(res.data, this)
          })
          .catch(() => {
            this.loading = false
          })
      },
      //导出
      exportFunc() {
        this.downloadModal = true
      },
    },
  }
</script>

<style lang="scss">
  @import '@/ve/styles/elements.scss';
  @import '@/ve/elements/basic/uiTable/style.scss';

  .default-theme {
    .el-form {
      .el-range-editor--small .el-range-separator {
        line-height: 20px;
        font-size: 13px;
      }
      .el-range-editor--small.el-input__inner {
        height: 26px;
      }
      .el-form-item--small.el-form-item {
        margin-bottom: 0px;
      }
      .el-form-item--small.el-form-item {
        margin-bottom: 0px;
      }
      .el-input--small .el-input__inner {
        height: 26px;
      }
      .el-form-item--small .el-form-item__content {
        line-height: 26px;
      }
      .el-form-item--small .el-form-item__label {
        line-height: 26px;
      }
    }
    .buttonGroup {
      margin-top: 6px;
      display: flex;
      justify-content: space-between;
      // 表格样式
      .vxe-button.size--mini.refresh-btn,
      .vui-toolbar-box .vxe-button.size--mini.refresh-btn,
      .vxe-button.type--button.is--circle {
        border-radius: 4px;
        border-color: #3270ff;

        .vxe-button--content,
        .vxe-button--icon {
          color: #3270ff;
        }
      }
      .vxe-button.size--mini.refresh-btn {
        height: 20px;
        width: 20px;
        padding: 0;
        margin-left: 6px;
      }
      .vxe-custom--option-wrapper {
        display: none;
        position: absolute;
        right: 4px;
        top: 40px;
        text-align: left;
        background-color: #fff;
        z-index: 19;
        border: 1px solid #e8eaec;
        border-radius: 4px;
        box-shadow: 0 1px 6px rgb(0 0 0 / 20%);
      }
      .vxe-custom--option-wrapper.is--active {
        display: block;
      }
      .vxe-custom--option-wrapper .vxe-custom--body {
        padding: 0.2em;
        max-height: 6.6em;
      }

      .vxe-custom--option-wrapper .vxe-custom--header {
        padding: 0;
        border-bottom: 1px solid #dadce0;
      }
      .vxe-custom--option-wrapper .vxe-custom--header li {
        max-width: 16em;
        min-width: 12.5em;
        padding: 2px 1em 2px 26px;
      }
      .custom-item-drag {
        position: absolute;
        top: 4px;
        left: 2px;
        color: #dedede;
        background-color: transparent;
      }
      // .vxe-custom--header .vxe-custom--option .vxe-checkbox--icon {
      //   left: 5px;
      //   top: 8px;
      // }
      // .vxe-custom--header .vxe-checkbox--label {
      //   font-weight: 400;
      //   font-size: 12px;
      // }
      .vxe-custom--option-wrapper .vxe-custom--body {
        padding: 0.2em;
        max-height: 6.6em;
      }
      .vxe-custom--option-wrapper .vxe-custom--body.large {
        max-height: 10.6em;
      }
      .vxe-custom--option-wrapper .vxe-custom--body li {
        position: relative;
        padding: 6px 0 6px 44px;
        font-size: 12px;
      }
      .vxe-custom--option-wrapper .vxe-custom--body li:hover {
        background: #eceff5;
      }
      .vxe-custom--option-wrapper .vxe-custom--footer {
        padding: 4px 0;
      }
      .vxe-custom--option-wrapper .vxe-custom--footer button.save-table-btn {
        background-color: #fff;
        color: #3270ff;
        font-size: 10px;
        margin: 4px;
        padding: 6px 14px;
        height: auto;
        border-radius: 2px;
        border: 1px solid #3270ff;
        width: auto;
      }
      .vxe-custom--option-wrapper .vxe-custom--footer button.save-db-data {
        background-color: #3270ff;
        color: #fff;
      }
    }
    .tableContent {
      height: calc(100% - 56px);
    }
  }
</style>
